import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {
  InboundServicesService,
  InboundManageDTO,
  CreateUpdateInboundManageDTO,
  CreateUpdateInboundDetailDto,
  ProductDto,
  InboundOperationLogDto,
  ApprovalHistoryDto,
  LogService,
  ApprovalHistoryService,
  InboundOperationLogService,
  PurchaseOrderService,
  ReturnOrderService,
  AllocateService
} from '../../../proxy/storage';
import { PagedResultDto } from '@abp/ng.core';
import { DialogService } from 'primeng/dynamicdialog';
import { ProductEditDialogComponent } from './product-edit-dialog.component';
import { ProductSelectModalComponent } from './product-select-modal.component';
import { OrderSelectDialogComponent } from './order-select-dialog.component';
import { MessageService, ConfirmationService } from 'primeng/api';
import { DocumentStatusPipe } from './document-status.pipe';

// PrimeNG Modules
import { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
import { DialogModule } from 'primeng/dialog';
import { InputTextModule } from 'primeng/inputtext';
import { CalendarModule } from 'primeng/calendar';
import { DropdownModule } from 'primeng/dropdown';
import { FileUploadModule } from 'primeng/fileupload';
import { ToastModule } from 'primeng/toast';
import { ConfirmDialogModule } from 'primeng/confirmdialog';
import { DynamicDialogModule } from 'primeng/dynamicdialog';
import { CheckboxModule } from 'primeng/checkbox';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-inbound-manage',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    TableModule,
    ButtonModule,
    DialogModule,
    InputTextModule,
    CalendarModule,
    DropdownModule,
    FileUploadModule,
    ToastModule,
    ConfirmDialogModule,
    DynamicDialogModule,
    CheckboxModule,
    DocumentStatusPipe,
    ProductEditDialogComponent,
    ProductSelectModalComponent,
    OrderSelectDialogComponent
  ],
  providers: [
    DialogService,
    MessageService,
    ConfirmationService,
    InboundServicesService,
    LogService,
    ApprovalHistoryService,
    InboundOperationLogService,
    PurchaseOrderService,
    ReturnOrderService,
    AllocateService
  ],
  templateUrl: './inbound-manage.component.html',
  styleUrls: ['./inbound-manage.component.scss']
})
export class InboundManageComponent implements OnInit {
  inboundList: InboundManageDTO[] = [];
  totalCount = 0;
  loading = false;
  searchKeyword = '';
  currentPage = 1;
  pageSize = 10;

  // 新增/编辑表单
  showForm = false;
  isEdit = false;
  currentItem: InboundManageDTO | null = null;

  // 审批对话框
  showApprovalDialog = false;
  approvalItem: InboundManageDTO | null = null;
  approvalComment = '';
  approvalState = 1; // 1: 同意, 3: 拒绝

  // 表单数据
  formData: CreateUpdateInboundManageDTO = {
    inboundOrderNumber: '',
    inboundType: '',
    state: 0,
    inboundDate: new Date().toISOString(),
    warehouseName: '',
    inboundGood: '',
    attn: '',
    inboundQuantity: 0,
    inboundAmount: 0,
    makeSingle: '',
    makeSingleTime: new Date().toISOString(),
    details: [],
    goodsNumber: 0,
    contactPhone: '',
    relatedOrderNo: '',
    supplierName: '',
    contactPerson: '',
    reviewers: '',
    reviewTime: ''
  };

  // 入库类型选项
  inboundTypes = [
    { value: '采购入库', label: '采购入库' },
    { value: '退货入库', label: '退货入库' },
    { value: '调拨入库', label: '调拨入库' },
    { value: '其他入库', label: '其他入库' }
  ];

  // 状态选项
  states = [
    { value: 0, label: '单据状态' },
    { value: 1, label: '草稿' },
    { value: 2, label: '待审核' },
    { value: 3, label: '已拒绝' },
    { value: 4, label: '已完成' }
  ];

  // Math对象引用
  Math = Math;

  details: any[] = [];

  uploadedFiles: any[] = [];

  operationLogs: InboundOperationLogDto[] = [];
  approvalHistories: ApprovalHistoryDto[] = [];
  recordTab: 'operation' | 'approval' | 'detail' = 'detail';

  isSaving = false; // 添加保存状态标志

  // 选择单据弹窗相关
  get showOrderSelectBtn() {
    return (
      this.formData.inboundType === '采购入库' ||
      this.formData.inboundType === '退货入库' ||
      this.formData.inboundType === '调拨入库'
    );
  }

  warehouseOptions = [
    { label: '葫芦岛', value: '葫芦岛' },
    { label: '章鱼堡', value: '章鱼堡' },
    { label: '仓库1', value: '仓库1' }
  ];

  constructor(
    private inboundService: InboundServicesService,
    private dialogService: DialogService,
    private logService: LogService,
    private approvalHistoryService: ApprovalHistoryService,
    private inboundOperationLogService: InboundOperationLogService,
    private messageService: MessageService,
    private confirmationService: ConfirmationService,
    private purchaseOrderService: PurchaseOrderService,
    private returnOrderService: ReturnOrderService,
    private allocateService: AllocateService
  ) { }

  ngOnInit(): void {
    this.loadData();
  }

  loadData(): void {
    this.loading = true;
    const input: any = {
      skipCount: (this.currentPage - 1) * this.pageSize,
      maxResultCount: this.pageSize,
      keyword: this.searchKeyword
    };

    console.log('加载数据:', input, '当前页:', this.currentPage);

    this.inboundService.getList(input).subscribe({
      next: (result: PagedResultDto<InboundManageDTO>) => {
        this.inboundList = result.items || [];
        this.totalCount = result.totalCount || 0;
        this.loading = false;
        console.log('数据加载完成:', this.totalCount, '条记录');
      },
      error: (error) => {
        console.error('加载数据失败:', error);
        this.loading = false;
      }
    });
  }

  search(): void {
    this.currentPage = 1;
    this.loadData();
  }

  onPageChange(page: number): void {
    this.currentPage = page;
    this.loadData();
  }

  getTotalPages(): number {
    return Math.ceil(this.totalCount / this.pageSize);
  }

  getPageNumbers(): number[] {
    const totalPages = this.getTotalPages();
    const pages: number[] = [];

    // 简化版本：只显示前5页和后5页
    for (let i = 1; i <= Math.min(5, totalPages); i++) {
      pages.push(i);
    }

    if (totalPages > 5) {
      pages.push(-1); // 省略号
      for (let i = Math.max(6, totalPages - 4); i <= totalPages; i++) {
        pages.push(i);
      }
    }

    return pages;
  }

  addNew(): void {
    this.isEdit = false;
    this.currentItem = null;
    this.resetForm();
    this.details = [];
    this.recordTab = 'detail';
    this.showForm = true;
  }

  editItem(item: InboundManageDTO): void {
    this.isEdit = true;
    this.currentItem = item;
    this.inboundService.get(item.id!).subscribe({
      next: (fullData) => {
        const fullDataAny = fullData as any;
        this.formData = {
          inboundOrderNumber: fullData.inboundOrderNumber || '',
          inboundType: fullData.inboundType || '',
          state: fullData.state,
          inboundDate: fullData.inboundDate || '',
          warehouseName: fullData.warehouseName || '',
          inboundGood: fullData.inboundGood || '',
          attn: fullData.attn || '',
          inboundQuantity: fullData.inboundQuantity || 0,
          inboundAmount: fullData.inboundAmount || 0,
          makeSingle: fullData.makeSingle || '',
          makeSingleTime: fullData.makeSingleTime || '',
          details: fullData.details ? fullData.details.map((d: any) => ({
            productId: d.productId || '00000000-0000-0000-0000-000000000000',
            productName: d.productName || '',
            productCode: d.productCode || '',
            productType: d.productType || '',
            model: d.model || '',
            unit: d.unit || '个',
            location: d.location || '',
            unitPrice: d.unitPrice || 0,
            quantity: d.quantity || 0,
            amount: d.amount || 0,
            stockBefore: d.stockBefore || 0,
            stockAfter: d.stockAfter || 0,
            batchNumber: d.batchNumber || '-',
            productionDate: d.productionDate || new Date().toISOString().split('T')[0],
            remarks: d.remarks || ''
          })) : [],
          goodsNumber: fullDataAny.goodsNumber || 0,
          contactPhone: fullData.contactPhone || '',
          relatedOrderNo: fullData.relatedOrderNo || (fullData.inboundType === '调拨入库' ? fullDataAny.allocateCode || '' : ''),
          supplierName: fullData.supplierName || (fullData.inboundType === '调拨入库' ? fullDataAny.allocationSector || '' : ''),
          contactPerson: fullData.contactPerson || (fullData.inboundType === '调拨入库' ? fullDataAny.transferor || '' : ''),
          reviewers: fullData.reviewers || '',
          reviewTime: fullData.reviewTime || ''
        };
        console.log('formData after get:', this.formData);
        this.details = this.formData.details;
        console.log('details after assign:', this.details);
        this.showForm = true;

        // 加载操作记录
        if (item.id) {
          this.loadOperationLogs(item.id);
        }

        // 加载审批记录（如果需要的话）
        if (item.id && item.state !== 1) { // 只有非草稿状态才加载审批记录
          this.loadApprovalHistories(item.id);
        }
      },
      error: (error) => {
        console.error('获取入库单详情失败:', error);
        this.messageService.add({
          severity: 'error',
          summary: '错误',
          detail: '获取入库单详情失败'
        });
      }
    });
  }

  deleteItem(id: string): void {
    alert('deleteItem: ' + id);
    console.log('deleteItem clicked, id:', id);
    this.confirmationService.confirm({
      message: '确定要删除这条入库记录吗？',
      header: '删除确认',
      icon: 'pi pi-exclamation-triangle',
      acceptLabel: '确定',
      rejectLabel: '取消',
      accept: () => {
        this.inboundService.delete(id).subscribe({
          next: () => {
            this.loadData();
            this.messageService.add({ severity: 'success', summary: '成功', detail: '删除成功', life: 2000 });
            this.logService.log(
              this.getCurrentUser(),
              '删除',
              `删除入库单：${id}`,
              id
            ).subscribe(() => this.loadOperationLogs(id));
          },
          error: (error) => {
            this.messageService.add({ severity: 'error', summary: '失败', detail: '删除失败', life: 2000 });
            console.error('删除失败:', error);
          }
        });
      }
    });
  }

  validateForm(): boolean {
    if (!this.formData.inboundType) {
      this.messageService.add({severity: 'error', summary: '错误', detail: '请选择入库类型'});
      return false;
    }
    if (!this.formData.warehouseName) {
      this.messageService.add({severity: 'error', summary: '错误', detail: '请输入仓库名称'});
      return false;
    }
    if (!this.formData.inboundGood) {
      this.messageService.add({severity: 'error', summary: '错误', detail: '请输入入库商品'});
      return false;
    }
    if (!this.formData.attn) {
      this.messageService.add({severity: 'error', summary: '错误', detail: '请输入负责人'});
      return false;
    }
    if (this.formData.inboundQuantity <= 0) {
      this.messageService.add({severity: 'error', summary: '错误', detail: '入库数量必须大于0'});
      return false;
    }
    if (this.formData.inboundAmount <= 0) {
      this.messageService.add({severity: 'error', summary: '错误', detail: '入库金额必须大于0'});
      return false;
    }
    return true;
  }

  saveForm(): void {
    if (this.isSaving) {
      return;
    }

    // 严格校验主表字段，不能为 'string'、空字符串、undefined
    const mainFields = [
      'inboundOrderNumber', 'inboundType', 'warehouseName', 'inboundGood', 'attn', 'makeSingle', 'makeSingleTime'
    ];
    for (const field of mainFields) {
      const value = this.formData[field];
      if (value === undefined || value === null || value === '' || value === 'string') {
        this.messageService.add({ severity: 'error', summary: '错误', detail: `主表字段 ${field} 不能为空或为'string'` });
        return;
      }
    }
    if (this.formData.inboundQuantity <= 0) {
      this.messageService.add({ severity: 'error', summary: '错误', detail: '入库数量必须大于0' });
      return;
    }
    if (this.formData.inboundAmount <= 0) {
      this.messageService.add({ severity: 'error', summary: '错误', detail: '入库金额必须大于0' });
      return;
    }
    if (!Array.isArray(this.details) || this.details.length === 0) {
      this.messageService.add({ severity: 'error', summary: '错误', detail: '请添加入库明细' });
      return;
    }
    // 明细校验
    for (let i = 0; i < this.details.length; i++) {
      const detail = this.details[i];
      if (!detail.productId || typeof detail.productId !== 'string' || detail.productId.length !== 36 || detail.productId === 'string') {
        this.messageService.add({ severity: 'error', summary: '错误', detail: `第${i + 1}行明细的商品ID无效` });
        return;
      }
      const detailFields = [
        'productName', 'productCode', 'productType', 'model', 'unit', 'location', 'batchNumber', 'productionDate', 'remarks'
      ];
      for (const f of detailFields) {
        if (detail[f] === undefined || detail[f] === null || detail[f] === 'string') {
          this.messageService.add({ severity: 'error', summary: '错误', detail: `第${i + 1}行明细的${f}不能为空或为'string'` });
          return;
        }
      }
      if (!detail.quantity || detail.quantity <= 0) {
        this.messageService.add({ severity: 'error', summary: '错误', detail: `第${i + 1}行明细的数量必须大于0` });
        return;
      }
      if (detail.unitPrice === undefined || detail.unitPrice === null || detail.unitPrice < 0) {
        this.messageService.add({ severity: 'error', summary: '错误', detail: `第${i + 1}行明细的单价不能为负` });
        return;
      }
    }

    console.log('保存按钮被点击');
    console.log('当前表单数据:', this.formData);
    console.log('当前明细数据:', this.details);

    try {
      // 检查必填字段
      const requiredFields = [
        { field: 'inboundType', message: '请选择入库类型' },
        { field: 'warehouseName', message: '请选择仓库' },
        { field: 'attn', message: '请输入负责人' },
        { field: 'inboundGood', message: '请输入入库商品' }
      ];

      for (const { field, message } of requiredFields) {
        if (!this.formData[field]) {
          this.messageService.add({ severity: 'error', summary: '错误', detail: message });
          console.log(`${field} 未填写`);
          return;
        }
      }

      if (this.details.length === 0) {
        this.messageService.add({ severity: 'error', summary: '错误', detail: '请添加入库明细' });
        console.log('入库明细为空');
        return;
      }

      // 验证明细数据
      for (let i = 0; i < this.details.length; i++) {
        const detail = this.details[i];
        if (!detail.productId || detail.productId.length !== 36) {  // GUID应该是36个字符
          this.messageService.add({ severity: 'error', summary: '错误', detail: `第 ${i + 1} 行商品ID无效` });
          console.log(`第 ${i + 1} 行商品ID无效:`, detail.productId);
          return;
        }
        if (!detail.quantity || detail.quantity <= 0) {
          this.messageService.add({ severity: 'error', summary: '错误', detail: `第 ${i + 1} 行数量必须大于0` });
          return;
        }
        if (detail.unitPrice === undefined || detail.unitPrice === null || detail.unitPrice < 0) {
          this.messageService.add({ severity: 'error', summary: '错误', detail: `第 ${i + 1} 行单价不能为负` });
          return;
        }
      }

      this.isSaving = true;

      // 设置状态为草稿
      if (!this.isEdit) {
        this.formData.state = 1;
      }

      // 设置制单信息
      if (!this.formData.makeSingle) {
        this.formData.makeSingle = this.getCurrentUser();
      }
      this.formData.makeSingleTime = new Date().toISOString();

      // 处理明细数据，严格按 CreateUpdateInboundDetailDto 组装
      this.formData.details = this.details.map(detail => {
        const result: any = {
          productId: detail.productId,
          productName: detail.productName || '',
          productCode: detail.productCode || '',
          productType: detail.productType || '',
          model: detail.model || '',
          unit: detail.unit || '个',
          location: detail.location || '',
          unitPrice: Number(detail.unitPrice) || 0,
          quantity: Number(detail.quantity) || 0,
          amount: Number(detail.amount) || 0,
          stockBefore: Number(detail.stockBefore) || 0,
          stockAfter: Number(detail.stockAfter) || 0,
          batchNumber: detail.batchNumber || '-',
          productionDate: detail.productionDate || new Date().toISOString(),
          remarks: detail.remarks || ''
        };
        // 编辑时带上id
        if (this.isEdit && detail.id) {
          result.id = detail.id;
        }
        return result;
      });

      // 重新计算总数量和总金额
      this.formData.inboundQuantity = this.formData.details.reduce((sum, detail) => sum + Number(detail.quantity), 0);
      this.formData.inboundAmount = this.formData.details.reduce((sum, detail) => sum + Number(detail.amount), 0);
      this.formData.goodsNumber = this.formData.details.length;

      // 不传 files 字段（后端 DTO 没有）
      // this.formData.files = ... // 注释掉

      // 确保日期字段格式正确
      if (this.formData.inboundDate) {
        this.formData.inboundDate = new Date(this.formData.inboundDate).toISOString();
      }

      // 只保留 DTO 里有的字段
      const dto: any = {
        inboundOrderNumber: this.formData.inboundOrderNumber,
        inboundType: this.formData.inboundType,
        state: this.formData.state,
        inboundDate: this.formData.inboundDate,
        warehouseName: this.formData.warehouseName,
        inboundGood: this.formData.inboundGood,
        attn: this.formData.attn,
        inboundQuantity: this.formData.inboundQuantity,
        inboundAmount: this.formData.inboundAmount,
        makeSingle: this.formData.makeSingle,
        makeSingleTime: this.formData.makeSingleTime,
        details: this.formData.details,
        goodsNumber: this.formData.goodsNumber,
        contactPhone: this.formData.contactPhone,
        relatedOrderNo: this.formData.relatedOrderNo,
        supplierName: this.formData.supplierName,
        contactPerson: this.formData.contactPerson,
        reviewers: this.formData.reviewers,
        reviewTime: this.formData.reviewTime
      };

      // 移除 undefined 字段
      Object.keys(dto).forEach(key => {
        if (dto[key] === undefined) {
          delete dto[key];
        }
      });

      console.log('准备发送的完整数据:', JSON.stringify(dto, null, 2));

      const saveRequest = this.isEdit
        ? this.inboundService.update(this.currentItem!.id!, dto)
        : this.inboundService.create(dto);

      saveRequest.subscribe({
        next: (result) => {
          console.log('保存成功，返回数据:', result);
          this.messageService.add({
            severity: 'success',
            summary: '成功',
            detail: `${this.isEdit ? '更新' : '创建'}入库单成功`
          });
          this.showForm = false;
          this.loadData();
          this.isSaving = false;
        },
        error: (error) => {
          console.error('保存失败:', error);
          let errorMessage = `${this.isEdit ? '更新' : '创建'}入库单失败`;
          if (error.error?.message) {
            errorMessage += `: ${error.error.message}`;
          } else if (error.message) {
            errorMessage += `: ${error.message}`;
          } else {
            errorMessage += ': 未知错误';
          }
          this.messageService.add({
            severity: 'error',
            summary: '错误',
            detail: errorMessage
          });
          this.isSaving = false;
        }
      });
    } catch (error) {
      console.error('保存过程中发生错误:', error);
      this.messageService.add({
        severity: 'error',
        summary: '错误',
        detail: '保存过程中发生错误'
      });
      this.isSaving = false;
    }
  }

  cancelForm(): void {
    this.showForm = false;
    this.resetForm();
  }

  private resetForm(): void {
    const now = new Date();
    const nowString = now.toISOString().slice(0, 16); // 格式化为 YYYY-MM-DDTHH:mm

    this.formData = {
      inboundOrderNumber: this.generateUniqueOrderNumber(),
      inboundType: '',
      state: 1, // 状态默认为 1，即 "草稿"
      inboundDate: now.toISOString(), // 自动设置为当前日期
      warehouseName: '',
      inboundGood: '',
      attn: '',
      inboundQuantity: 0,
      inboundAmount: 0,
      makeSingle: this.getCurrentUser(),
      makeSingleTime: now.toISOString(), // 自动设置为当前时间
      details: [],
      goodsNumber: 0,
      contactPhone: '',
      relatedOrderNo: '',
      supplierName: '',
      contactPerson: '',
      reviewers: '',
      reviewTime: ''
    };
    this.details = [];
  }

  private generateUniqueOrderNumber(): string {
    let orderNumber = '';
    let isUnique = false;
    const existingNumbers = new Set(this.inboundList.map(item => item.inboundOrderNumber));

    while (!isUnique) {
      const randomNumber = Math.floor(100000 + Math.random() * 900000).toString();
      orderNumber = `RKDH${randomNumber}`;

      if (!existingNumbers.has(orderNumber)) {
        isUnique = true;
      }
    }

    return orderNumber;
  }

  getStateLabel(state: number): string {
    const stateItem = this.states.find(s => s.value === state);
    return stateItem ? stateItem.label : '未知状态';
  }

  getStateClass(state: number): string {
    switch (state) {
      case 0:
        return 'status-default';
      case 1:
        return 'status-draft';
      case 2:
        return 'status-pending';
      case 3:
        return 'status-rejected';
      case 4:
        return 'status-completed';
      default:
        return 'status-default';
    }
  }

  exportExcel(): void {
    this.inboundService.exportToExcel().subscribe({
      next: (blob: Blob) => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = '入库管理.xlsx';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        this.logService.log(
          this.getCurrentUser(),
          '导出',
          '导出入库单Excel'
        ).subscribe();
      },
      error: (error) => {
        console.error('导出失败:', error);
        alert('导出失败');
      }
    });
  }

  // 审批相关方法
  showApproval(item: InboundManageDTO): void {
    this.approvalItem = item;
    this.approvalComment = '';
    this.approvalState = 1;
    this.showApprovalDialog = true;
  }

  submitApproval(): void {
    if (!this.approvalItem || !this.approvalComment) {
      this.messageService.add({
        severity: 'error',
        summary: '错误',
        detail: '请填写审批意见'
      });
      return;
    }

    const approvalData = {
      id: this.approvalItem.id,
      state: this.approvalState,
      comment: this.approvalComment,
      approver: this.getCurrentUser(),
      approvalTime: new Date().toISOString()
    };

    this.inboundService.approve(this.approvalItem.id!, approvalData).subscribe({
      next: () => {
        this.messageService.add({
          severity: 'success',
          summary: '成功',
          detail: '审批完成'
        });
        this.showApprovalDialog = false;
        this.loadData();
        
        // 记录审批历史
        this.approvalHistoryService.create({
          documentId: this.approvalItem!.id!,
          documentType: 'InboundOrder',
          approver: this.getCurrentUser(),
          approvalTime: new Date().toISOString(),
          approvalState: this.approvalState,
          approvalComment: this.approvalComment
        }).subscribe();
      },
      error: (error) => {
        console.error('审批失败:', error);
        this.messageService.add({
          severity: 'error',
          summary: '错误',
          detail: '审批失败: ' + (error.message || '未知错误')
        });
      }
    });
  }

  cancelApproval(): void {
    this.showApprovalDialog = false;
    this.approvalItem = null;
    this.approvalComment = '';
  }

  canApprove(item: InboundManageDTO): boolean {
    return item.state === 2; // 只有待审核状态可以审批
  }

  openProductModal() {
    const ref = this.dialogService.open(ProductSelectModalComponent, {
      header: '选择货品',
      width: '800px',
      closable: true,
      data: {}
    });
    ref.onClose.subscribe((selectedProducts) => {
      if (selectedProducts && selectedProducts.length > 0) {
        this.onProductSelect(selectedProducts);
      }
    });
  }

  onProductSelect(products: ProductDto[]) {
    products.forEach(product => {
      if (!this.details.find(d => d.productId === product.id)) {
        const detail = {
          productId: product.id || '00000000-0000-0000-0000-000000000000', // 确保是GUID格式
          productName: product.productName || '',
          productCode: product.productCode || '',
          productType: product.productType || '',
          model: product.model || '',
          unit: product.unit || '个',
          location: '',
          unitPrice: 0, // 默认为0，因为ProductDto中没有unitPrice字段
          quantity: 1,
          amount: 0, // 初始金额为0
          batchNumber: '-',
          productionDate: new Date().toISOString().split('T')[0],
          remarks: ''
        };
        this.details.push(detail);
        this.updateAmount(detail);
      }
    });

    // 更新主表数据
    this.formData.inboundQuantity = this.details.reduce((sum, d) => sum + (Number(d.quantity) || 0), 0);
    this.formData.inboundAmount = this.details.reduce((sum, d) => sum + (Number(d.amount) || 0), 0);
    this.formData.goodsNumber = this.details.length;
  }

  save() {
    // 校验
    // ...
    // this.inboundService.create({ ...主表字段, details: this.details }).subscribe(...)
    console.log('提交数据', this.details);
  }

  openProductEditDialog() {
    this.dialogService.open(ProductEditDialogComponent, {
      header: '新增货品',
      width: '400px',
      data: {}
    }).onClose.subscribe((result: any) => {
      if (result) {
        this.details.push({
          ...result,
          batchNumber: '-',
        });
      }
    });
  }

  updateAmount(detail: any): void {
    detail.quantity = Number(detail.quantity) || 0;
    detail.unitPrice = Number(detail.unitPrice) || 0;
    detail.amount = detail.quantity * detail.unitPrice;
  }

  removeDetail(index: number): void {
    this.details.splice(index, 1);
  }

  getTotalAmount(): number {
    return this.details.reduce((sum, d) => sum + (Number(d.amount) || 0), 0);
  }

  switchRecordTab(tab: 'operation' | 'approval' | 'detail') {
    this.recordTab = tab;
  }

  getCurrentUser(): string {
    // 实际项目可从登录信息获取
    return localStorage.getItem('abp.userName') || '匿名';
  }

  loadOperationLogs(inboundId: string) {
    this.inboundOperationLogService.getList({
      sorting: '',
      skipCount: 0,
      maxResultCount: 1000,
      inboundManageId: inboundId
    }).subscribe({
      next: (res) => {
        this.operationLogs = res.items || [];
      },
      error: (error) => {
        console.error('加载操作记录失败:', error);
      }
    });
  }

  loadApprovalHistories(inboundId: string) {
    // 如果是草稿状态，不加载审批记录
    if (this.formData.state === 1) {
      this.approvalHistories = [];
      return;
    }

    // 使用 try-catch 包装 API 调用
    try {
      this.approvalHistoryService.getListByInboundId(inboundId).subscribe({
        next: (res) => {
          this.approvalHistories = res || [];
          console.log('审批历史记录:', this.approvalHistories);
        },
        error: (error) => {
          console.error('加载审批记录失败:', error);
          this.approvalHistories = []; // 出错时设置为空数组
          // 不显示错误提示，因为这不是关键功能
        }
      });
    } catch (error) {
      console.error('调用审批记录服务失败:', error);
      this.approvalHistories = []; // 出错时设置为空数组
    }
  }

  openOrderSelectDialog() {
    let typeLabel = '';
    let getOrders$: Observable<PagedResultDto<any>>;
    
    if (this.formData.inboundType === '采购入库') {
      typeLabel = '采购单';
      getOrders$ = this.purchaseOrderService.getList({ skipCount: 0, maxResultCount: 20 });
    } else if (this.formData.inboundType === '退货入库') {
      typeLabel = '退货单';
      getOrders$ = this.returnOrderService.getList({ skipCount: 0, maxResultCount: 20 });
    } else if (this.formData.inboundType === '调拨入库') {
      typeLabel = '调拨单';
      getOrders$ = this.allocateService.getList({ skipCount: 0, maxResultCount: 20 });
    } else {
      this.messageService.add({ severity: 'info', summary: '提示', detail: '当前类型无需选择单据', life: 2000 });
      return;
    }

    getOrders$.subscribe((res: PagedResultDto<any>) => {
      const ref = this.dialogService.open(OrderSelectDialogComponent, {
        header: `选择${typeLabel}`,
        width: '80%',
        contentStyle: { 'max-height': '500px', 'overflow': 'auto' },
        baseZIndex: 10000,
        data: { 
          orders: res.items.map(order => {
            let mappedOrder = {
              orderNumber: '',
              name: '',
              vendor: '',
              quantity: 0,
              amount: 0,
              phone: '',
              returners: '',
              purchaser: ''
            };
            switch (this.formData.inboundType) {
              case '采购入库':
                mappedOrder = {
                  orderNumber: order.purchaseNumner,
                  name: order.purchaseOrderName,
                  vendor: order.vendor,
                  quantity: order.goodsNumber,
                  amount: order.amountPurchase,
                  phone: order.phone,
                  returners: '',
                  purchaser: order.purchaser
                };
                break;
              case '退货入库':
                mappedOrder = {
                  orderNumber: order.returnOrderNumber,
                  name: order.returnOrderName,
                  vendor: order.returners,
                  quantity: order.returnsNumber,
                  amount: order.returnAmount,
                  phone: order.phone,
                  returners: order.returnee,
                  purchaser: ''
                };
                break;
              case '调拨入库':
                mappedOrder = {
                  orderNumber: order.allocateCode,
                  name: order.allocateName,
                  vendor: order.vendor,
                  quantity: order.transfersAmount,
                  amount: order.allocateAmount,
                  phone: order.phone,
                  returners: '',
                  purchaser: ''
                };
                break;
            }
            return mappedOrder;
          })
        }
      });

      ref.onClose.subscribe((selectedOrder: any) => {
        if (selectedOrder) {
          this.formData.relatedOrderNo = selectedOrder.orderNumber;
          this.formData.supplierName = selectedOrder.vendor;
          // 采购入库联系人用purchaser，退货入库用returners，其他用name
          if (this.formData.inboundType === '采购入库') {
            this.formData.contactPerson = selectedOrder.purchaser;
          } else if (this.formData.inboundType === '退货入库') {
            this.formData.contactPerson = selectedOrder.returners;
          } else {
            this.formData.contactPerson = selectedOrder.name;
          }
          this.formData.contactPhone = selectedOrder.phone;
          this.formData.inboundAmount = selectedOrder.amount;
          this.formData.inboundQuantity = selectedOrder.quantity;
          this.formData.inboundGood = selectedOrder.name;
        }
      });
    });
  }

  onUpload(event: any) {
    const files = event.files;
    this.messageService.add({severity: 'info', summary: '成功', detail: '文件上传成功'});
  }

  onBeforeUpload(event: any) {
    // 可以在这里添加上传前的验证逻辑
    return true;
  }

  onError(event: any) {
    this.messageService.add({severity: 'error', summary: '错误', detail: '文件上传失败'});
  }

  onFileSelected(event: any) {
    const files = event.target.files;
    
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      
      // 模拟上传
      setTimeout(() => {
        this.uploadedFiles.push({
          name: file.name,
          size: file.size,
          url: `http://localhost:4200/fake-${file.name}`
        });
        
        this.messageService.add({
          severity: 'success',
          summary: '上传成功',
          detail: `${file.name} 上传成功（前端模拟）`
        });
      }, 500);
    }
    
    // 清空 input
    event.target.value = '';
  }

  removeFile(file: any) {
    const index = this.uploadedFiles.indexOf(file);
    if (index > -1) {
      this.uploadedFiles.splice(index, 1);
      this.messageService.add({
        severity: 'info',
        summary: '文件已移除',
        detail: `${file.name} 已从上传列表移除`
      });
    }
  }

  resetSearch() {
    this.searchKeyword = '';
    this.currentPage = 1;
    this.loadData();
  }
}